<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h1 class="logo">数学学习</h1>
        <p class="subtitle">创建新账号</p>
      </div>

      <div class="register-form">
        <div class="form-item">
          <input
            ref="phoneInput"
            v-model="phone"
            type="tel"
            placeholder="请输入手机号"
            maxlength="11"
            class="input"
            @blur="validatePhone"
            @keyup.enter="$refs.passwordInput?.focus()"
          />
          <div v-if="phoneError" class="error-msg">{{ phoneError }}</div>
        </div>

        <div class="form-item">
          <input
            ref="passwordInput"
            v-model="password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请设置密码（6-20位）"
            class="input"
            maxlength="20"
            @blur="validatePassword"
            @keyup.enter="$refs.confirmPasswordInput?.focus()"
          />
          <div class="password-toggle" @click="showPassword = !showPassword">
            <svg v-if="!showPassword" width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"/>
              <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.906 1.294L3.707 2.293zM14 10a4 4 0 01-4 4 4.01 4.01 0 01-2.316-.708l5.024-5.024A3.976 3.976 0 0114 10z" clip-rule="evenodd"/>
              <path d="M2.293 6.707A10.014 10.014 0 00.458 10c1.274 4.057 5.064 7 9.542 7 2.448 0 4.687-.831 6.43-2.207l-4.244-4.244A4 4 0 0110 8a4 4 0 00-4 4c0 .165.015.326.044.485L2.293 6.707z" clip-rule="evenodd"/>
            </svg>
          </div>
          <div v-if="passwordError" class="error-msg">{{ passwordError }}</div>
        </div>

        <div class="form-item">
          <input
            ref="confirmPasswordInput"
            v-model="confirmPassword"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请确认密码"
            class="input"
            maxlength="20"
            @blur="validateConfirmPassword"
            @keyup.enter="$refs.captchaInput?.focus()"
          />
          <div class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
            <svg v-if="!showConfirmPassword" width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"/>
              <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.906 1.294L3.707 2.293zM14 10a4 4 0 01-4 4 4.01 4.01 0 01-2.316-.708l5.024-5.024A3.976 3.976 0 0114 10z" clip-rule="evenodd"/>
              <path d="M2.293 6.707A10.014 10.014 0 00.458 10c1.274 4.057 5.064 7 9.542 7 2.448 0 4.687-.831 6.43-2.207l-4.244-4.244A4 4 0 0110 8a4 4 0 00-4 4c0 .165.015.326.044.485L2.293 6.707z" clip-rule="evenodd"/>
            </svg>
          </div>
          <div v-if="confirmPasswordError" class="error-msg">{{ confirmPasswordError }}</div>
        </div>

        <!-- 图片验证码 -->
        <div class="form-item">
          <div class="captcha-group">
            <input
              ref="captchaInput"
              v-model="captchaCode"
              type="text"
              placeholder="请输入验证码"
              class="input captcha-input"
              @blur="validateCaptchaCode"
              @keyup.enter="$refs.smsCodeInput?.focus()"
            />
            <div class="captcha-image" @click="loadCaptcha" v-html="captchaHtml"></div>
          </div>
          <div v-if="captchaCodeError" class="error-msg">{{ captchaCodeError }}</div>
        </div>

        <!-- 短信验证码 -->
        <div class="form-item">
          <div class="code-input-group">
            <input
              ref="smsCodeInput"
              v-model="smsCode"
              type="text"
              placeholder="请输入短信验证码"
              maxlength="6"
              class="input code-input"
              @blur="validateSmsCode"
              @keyup.enter="handleRegister"
            />
            <button
              :disabled="!canSendSms || sending"
              class="send-code-btn"
              @click="handleSendSmsCode"
            >
              {{ smsButtonText }}
            </button>
          </div>
          <div v-if="smsCodeError" class="error-msg">{{ smsCodeError }}</div>
        </div>

        <!-- 协议 -->
        <div class="form-item agreement">
          <label class="checkbox-label">
            <input
              v-model="agreeTerms"
              type="checkbox"
              class="checkbox"
            />
            <span>我已阅读并同意</span>
            <a href="#" class="link">《用户协议》</a>
            <span>和</span>
            <a href="#" class="link">《隐私政策》</a>
          </label>
          <div v-if="termsError" class="error-msg">{{ termsError }}</div>
        </div>

        <button
          :disabled="!canRegister || submitting"
          class="submit-btn"
          @click="handleRegister"
        >
          {{ submitting ? '注册中...' : '立即注册' }}
        </button>
      </div>

      <div class="register-footer">
        <span>已有账号？</span>
        <router-link to="/login" class="link">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getCaptcha, sendSmsCode, register } from '../api/auth'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 表单数据
const phone = ref('')
const password = ref('')
const confirmPassword = ref('')
const captchaCode = ref('')
const smsCode = ref('')
const agreeTerms = ref(false)

// 错误信息
const phoneError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const captchaCodeError = ref('')
const smsCodeError = ref('')
const termsError = ref('')

// 状态
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const sending = ref(false)
const submitting = ref(false)
const countdown = ref(0)
const captchaHtml = ref('')
const captchaToken = ref('')

onMounted(() => {
  // 如果从登录页传了手机号，自动填充
  if (route.query.phone) {
    phone.value = route.query.phone
  }
  // 加载图片验证码
  loadCaptcha()
})

// 计算属性
const canSendSms = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && 
         captchaCode.value && 
         countdown.value === 0 && 
         !phoneError.value && 
         !captchaCodeError.value
})

const canRegister = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) &&
         password.value.length >= 6 &&
         confirmPassword.value === password.value &&
         smsCode.value.length === 6 &&
         agreeTerms.value &&
         !phoneError.value &&
         !passwordError.value &&
         !confirmPasswordError.value &&
         !smsCodeError.value &&
         !termsError.value
})

const smsButtonText = computed(() => {
  if (countdown.value > 0) return `${countdown.value}秒后重试`
  if (sending.value) return '发送中...'
  return '获取验证码'
})

// 加载图片验证码
async function loadCaptcha() {
  try {
    const { data } = await getCaptcha()
    captchaHtml.value = data.html || data.svg || ''
    captchaToken.value = data.token || ''
  } catch (error) {
    console.error('加载验证码失败:', error)
  }
}

// 验证手机号
function validatePhone() {
  if (!phone.value) {
    phoneError.value = '请输入手机号'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    phoneError.value = '请输入正确的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

// 验证密码
function validatePassword() {
  if (!password.value) {
    passwordError.value = '请输入密码'
    return false
  }
  if (password.value.length < 6 || password.value.length > 20) {
    passwordError.value = '密码长度为6-20位'
    return false
  }
  if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(password.value)) {
    passwordError.value = '密码需包含字母和数字'
    return false
  }
  passwordError.value = ''
  return true
}

// 验证确认密码
function validateConfirmPassword() {
  if (!confirmPassword.value) {
    confirmPasswordError.value = '请确认密码'
    return false
  }
  if (confirmPassword.value !== password.value) {
    confirmPasswordError.value = '两次密码输入不一致'
    return false
  }
  confirmPasswordError.value = ''
  return true
}

// 验证图片验证码
function validateCaptchaCode() {
  if (!captchaCode.value) {
    captchaCodeError.value = '请输入图片验证码'
    return false
  }
  captchaCodeError.value = ''
  return true
}

// 验证短信验证码
function validateSmsCode() {
  if (!smsCode.value) {
    smsCodeError.value = '请输入短信验证码'
    return false
  }
  if (smsCode.value.length !== 6) {
    smsCodeError.value = '请输入6位验证码'
    return false
  }
  smsCodeError.value = ''
  return true
}

// 发送短信验证码
async function handleSendSmsCode() {
  if (!validatePhone() || !validateCaptchaCode()) return
  
  sending.value = true
  smsCodeError.value = ''
  
  try {
    const normalizedCaptcha = (captchaCode.value || '').trim().toLowerCase()
    await sendSmsCode({
      phone: String(phone.value),
      type: 'register',
      captchaCode: normalizedCaptcha
    }, captchaToken.value)
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    smsCodeError.value = error.message || '发送失败，请重试'
    // 刷新图片验证码
    loadCaptcha()
  } finally {
    sending.value = false
  }
}

// 注册
async function handleRegister() {
  console.log('注册按钮点击')
  console.log('表单数据:', {
    phone: phone.value,
    password: password.value,
    confirmPassword: confirmPassword.value,
    captchaCode: captchaCode.value,
    smsCode: smsCode.value,
    agreeTerms: agreeTerms.value
  })
  
  // 验证所有字段
  if (!validatePhone()) {
    console.log('手机号验证失败')
    return
  }
  if (!validatePassword()) {
    console.log('密码验证失败')
    return
  }
  if (!validateConfirmPassword()) {
    console.log('确认密码验证失败')
    return
  }
  if (!validateCaptchaCode()) {
    console.log('图片验证码验证失败')
    return
  }
  if (!validateSmsCode()) {
    console.log('短信验证码验证失败')
    return
  }
  
  if (!agreeTerms.value) {
    console.log('未同意协议')
    termsError.value = '请同意用户协议和隐私政策'
    return
  }
  
  console.log('所有验证通过，开始注册')
  submitting.value = true
  
  try {
    console.log('调用注册接口...')
    const normalizedCaptcha = (captchaCode.value || '').trim().toLowerCase()
    const { data } = await register({
      phone: String(phone.value),
      password: password.value,
      confirmPassword: confirmPassword.value,
      smsCode: smsCode.value,
      captchaCode: normalizedCaptcha,
      nickname: ''  // 可选，暂时留空
    }, captchaToken.value)
    console.log('注册成功:', data)
    userStore.setToken(data.token)
    userStore.setUserInfo(data.userInfo)
    
    // 注册成功，跳转到首页
    router.push('/home')
  } catch (error) {
    console.error('注册失败:', error)
    alert(error.message || '注册失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 440px;
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  max-height: 90vh;
  overflow-y: auto;
}

.register-header {
  text-align: center;
  margin-bottom: 32px;
  
  .logo {
    font-size: 32px;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 8px;
  }
  
  .subtitle {
    color: #666;
    font-size: 14px;
  }
}

.register-form {
  .form-item {
    margin-bottom: 20px;
    position: relative;
    
    &.agreement {
      margin-bottom: 24px;
    }
  }
  
  .input {
    width: 100%;
    padding: 14px 16px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.3s;
    
    &:focus {
      outline: none;
      border-color: #007AFF;
      box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
    }
  }
  
  .password-toggle {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    color: #999;
    
    &:hover {
      color: #666;
    }
  }
  
  .captcha-group {
    display: flex;
    gap: 12px;
    
    .captcha-input {
      flex: 1;
    }
    
    .captcha-image {
      width: 120px;
      height: 46px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      
      &:hover {
        border-color: #007AFF;
      }
    }
  }
  
  .code-input-group {
    display: flex;
    gap: 12px;
    
    .code-input {
      flex: 1;
    }
  }
  
  .send-code-btn {
    padding: 14px 24px;
    background: #007AFF;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover:not(:disabled) {
      background: #0051D5;
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
  
  .error-msg {
    color: #ff3b30;
    font-size: 13px;
    margin-top: 6px;
  }
  
  .checkbox-label {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
    cursor: pointer;
    
    .checkbox {
      margin-right: 8px;
      cursor: pointer;
    }
    
    .link {
      color: #007AFF;
      text-decoration: none;
      margin: 0 4px;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .submit-btn {
    width: 100%;
    padding: 16px;
    background: #007AFF;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    margin-top: 8px;
    
    &:hover:not(:disabled) {
      background: #0051D5;
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}

.register-footer {
  margin-top: 32px;
  text-align: center;
  color: #666;
  font-size: 14px;
  
  .link {
    color: #007AFF;
    text-decoration: none;
    margin-left: 8px;
    font-weight: 500;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 自定义checkbox样式 */
.checkbox {
  appearance: none;
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 4px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  
  &:checked {
    background: #007AFF;
    border-color: #007AFF;
    
    &::after {
      content: '';
      position: absolute;
      left: 5px;
      top: 2px;
      width: 5px;
      height: 10px;
      border: solid white;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
    }
  }
}
</style>



